package com.ohuang.jiaxiaotong.Activity;

import android.os.Bundle;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bunny.android.library.LoadDataLayout;
import com.example.myhttp.CallBackString;
import com.example.myhttp.Ihttp;
import com.ohuang.jiaxiaotong.Adapter.CollectRvAdapter;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.CollectUrl;
import com.ohuang.jiaxiaotong.entity.User;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;

public class CollectActivity extends BaseAc {
    private RecyclerView recyclerView;
    private User user;
    private CollectRvAdapter collectRvAdapter;
    private ArrayList<CollectUrl> mData;
    private LoadDataLayout loadDataLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collect);
        EventBus.getDefault().register(this);
        setTitle("收藏");
        Ohuang.changeStatusBarTextImgColor(this, true);
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.mipmap.icon_goback);//设置ActionBar返回按钮

        recyclerView = findViewById(R.id.rv_collect);
        loadDataLayout = findViewById(R.id.loadData_collect);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        loadDataLayout.showLoading("正在努力加载中", new LoadDataLayout.SetImgCallBack() {
            @Override
            public void setImg(ImageView img) {
                Glide.with(CollectActivity.this)
                        .load(R.drawable.gif_loading)
                        .into(img);
            }
        });//显示 load布局 状态正在加载
        if (user != null) {
            HttpGetClassUrl();
        }

    }



    //true为收藏 false为取消收藏
    private void httpCollectClassUrl(String id, boolean isCheck) {
        String aa;
        if (isCheck) {
            aa = "user/addCollect";
        } else {
            aa = "user/deleteCollect";
        }

        HashMap<String,String> map=new HashMap<>();
        map.put("dataId", id);
        map.put("username", user.getUsername());
        Ihttp.getInstance().post(MyHttpURL.mainUrl + aa, map, new CallBackString() {
            @Override
            public void success(String ojb) {

            }



            @Override
            public void fail(String s) {

            }
        });


    }


    private void HttpGetClassUrl() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("username", user.getUsername());


        service.GetClassUrl(map).enqueue(new Callback<ArrayList<CollectUrl>>() {
            @Override
            public void onResponse(Call<ArrayList<CollectUrl>> call, Response<ArrayList<CollectUrl>> response) {
                mData = response.body();
                if (mData.size() == 0) {
                    loadDataLayout.showEmpty();
                } else {
                    loadDataLayout.showSuccess();
                    collectRvAdapter = new CollectRvAdapter(CollectActivity.this, mData);
                    collectRvAdapter.setOnItemClickListener(new CollectRvAdapter.OnItemClickListener() {
                        @Override
                        public void CheckBoxOnCheckedChanged(CheckBox checkBox, int position, CompoundButton buttonView, boolean isChecked) {
                            if (isChecked) {
                                Toast.makeText(CollectActivity.this, "已收藏", Toast.LENGTH_SHORT).show();
                                httpCollectClassUrl(mData.get(position).getDataId() + "", true);
                            } else {
                                Toast.makeText(CollectActivity.this, "取消收藏", Toast.LENGTH_SHORT).show();
                                httpCollectClassUrl(mData.get(position).getDataId() + "", false);
                            }
                        }
                    });
                    recyclerView.setAdapter(collectRvAdapter);

                }
            }

            @Override
            public void onFailure(Call<ArrayList<CollectUrl>> call, Throwable t) {
                loadDataLayout.showError();
            }
        });
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {//左上角返回按钮
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    interface GithubService {
        //https://api.github.com/repos/{owner}/{repo}/contributors
        @POST("user/findCollect")
        Call<ArrayList<CollectUrl>> GetClassUrl(@QueryMap HashMap<String, String> deviceInfo);
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetUserEventBus(User user) {
        this.user = user;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
